<?php

namespace App\Wxaccount\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\Account;
use App\Store\Models\Member\Member;
use App\Store\Models\Wxapp\WxaccountSetting;
use EasyWeChat\OfficialAccount\Application;

class WxController extends Controller
{
    public function index(Request $request)
    {
        $content = file_get_contents('php://input');
        $cp_id = isset($_GET['cp_id']) ? intval($_GET['cp_id']) : 0;

        if ($cp_id > 0) {
            $setting = WxaccountSetting::query()->where([['cp_id', $cp_id]])->first();
        } else {
            // 取默认的配置
            $setting = WxaccountSetting::query()->where(['appid' => config('wx.wx_defult_appid')])->first();
        }


        $token = $setting->token ?? '';
        if (isset($_GET['nonce']) && isset($_GET['echostr']) && !empty($token)) {
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                echo $_GET["echostr"];
                exit;
            } else {
                return false;
            }
        } elseif ($content) {
            $content = simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA);
            $content = json_decode(json_encode($content), true);
            if (isset($content['Event'])) {
                if ($content['Event'] == 'subscribe') {
                    //关注
                    $openid = $content['FromUserName'];
                    $config = [
                        'app_id' => $setting->appid,
                        'secret' => $setting->appsecret,
                    ];
                    $wxapp = new Application($config);
                    $accessToken = $wxapp->getAccessToken();
                    $token = $accessToken->getToken();
                    $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $token . '&openid=' . $openid . '&lang=zh_CN');
                    $res = json_decode($res, true);

                    // 根据openid 查询用户
                    if (isset($res['unionid']) && !empty($res['unionid'])) {
                        $meminfo = Member::query()->where(['wx_unionid' => $res['unionid']])->first();
                        if (!empty($meminfo)) {
                            $meminfo = $meminfo->toArray();
                            Member::query()->where(['id' => $meminfo['id']])->update(['wx_account_open_id' => $openid]);
                            // 更新配置状态
                            WxaccountSetting::query()->where(['cp_id' => $cp_id])->update(['status' => 2]);
                        }
                    }

                    $url = env('WX_SUBSCRIBE_AUTH_URL') . '?wx_open_id=' . $openid . '&cp_id='.$cp_id;
                    echo '<xml>
                              <ToUserName><![CDATA[' . $openid . ']]></ToUserName>
                              <FromUserName><![CDATA[' . $content['ToUserName'] . ']]></FromUserName>
                              <CreateTime>' . time() . '</CreateTime>
                              <MsgType><![CDATA[text]]></MsgType>
                              <Content><![CDATA[' . ($setting->welcomemsg ? $setting->welcomemsg . "温馨提示:请点击下方链接进行授权\n" . $url : '欢迎关注') . ']]></Content>
                          </xml>';
                    exit;
                }

                if ($content['Event'] == 'unsubscribe') {
                    // 用户取消关注
                    $openid = $content['FromUserName'];
                    $meminfo = Member::where(['wx_account_open_id' => $openid])->first();
                    if (!empty($meminfo)) {
                        Member::where(['wx_account_open_id' => $openid])->update(['wx_account_open_id' => '']);
                    }

                    // 管理员取消关注
                    $account = Account::query()->where(['wx_account_openid' => $openid])->first();
                    if (!empty($account)) {
                        Account::query()->where(['wx_account_openid' => $openid])->update(['wx_account_openid' => '']);
                    }
                }

                exit;

            }

            // 管理员账号密码登录
            if (isset($content['MsgType']) && $content['MsgType'] == 'text' && $content['Content'] != '') {
                if (!empty($content['Content'])) {
                    $account = Account::query()->where(['account_name' => $content['Content']])->first();
                    if (!empty($account) && (int)$account->is_order_msg == 1) {
                        Account::query()->where(['account_name' => $content['Content']])->update(['wx_account_openid' => $content['FromUserName']]);
                        // 更新配置状态
                        WxaccountSetting::query()->where([['cp_id', $account['cp_id']]])->update(['status' => 2]);

                        echo '<xml>
                                    <ToUserName><![CDATA[' . $content['FromUserName'] . ']]></ToUserName>
                                    <FromUserName><![CDATA[' . $content['ToUserName'] . ']]></FromUserName>
                                    <CreateTime>' . time() . '</CreateTime>
                                    <MsgType><![CDATA[text]]></MsgType>
                                    <Content><![CDATA[绑定成功]]></Content>
                              </xml>';
                        exit;


                    }

                    exit;
                }

            }


        }


    }
}
